import validate from 'wechat-validate'
Page({
  data: {
    countDownVisible: false,
    mobile: '',
    code: '',
    status: ''
  },
  behaviors: [validate],
  rules: {
    mobile: [
      {required: true, message: '请填写手机号码!'},
      {pattern: /^1[3-9]\d{9}$/, message: '请填写正确的手机号码!'}
    ],
    code: [
      {required: true, message: '请填写验证码!'},
      {pattern: /^\d{6}$/, message: '请填写正确的验证码!'}
    ]
  },
  onLoad(query) {
    // console.log(query);
    this.query = query
    
  },


  countDownChange(ev) {
    // console.log(ev);
    
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  // 获取验证码
  async getSMSCode() {
     // 获取验证结果
     const {valid, message} = this.validate('mobile')
     // 如果验证不合法则不再执行后面的逻辑
     if(!valid) return wx.utils.toast(message)
     // 发送请求验证码 
    const res = await wx.http.get('/code', {mobile: this.data.mobile})
    console.log(res);
    this.setData({
      countDownVisible: true,
    })
    
  },
  // 登录表单提交
  async loginApp() {
    const {mobile, code} = this.data
    const isValidate = this.validate()
    if(!isValidate) return  
    // console.log(mobile, code)
    const res = await wx.http.post('/login', {mobile, code})
    const app = getApp()
    
    // app.token = res.data.token
    // wx.setStorageSync('token', res.data.token)
    if(res.code !== 10000) return wx.utils.toast(res.message)
    app.setToken('token', res.data.token)
    app.setToken('refreshToken', res.data.refreshToken)
    // 页面回跳
    console.log(this.query);
    
    wx.redirectTo({url: this.query.redirectUrl})
  }
})
